//
//  ViewController.m
//  UI20_音乐播放器_旋转图_滚动歌词
//
//  Created by dllo on 16/3/29.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "LrcParser.h"

@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain)UIImageView *backImage;

@property (nonatomic, retain)AVAudioPlayer *player;



@property (nonatomic, retain) NSTimer *firstTimer;

@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, assign) CGFloat a;
@property (nonatomic, retain) NSTimer *secTimer;

@property (nonatomic, retain) UITableView *lrcTable;
@property (nonatomic, retain) LrcParser *lrcContent;
@property (nonatomic, assign) NSInteger currentRow;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
#pragma mark 初始化播放器
    NSString *path = [[NSBundle mainBundle] pathForResource:@"演员" ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    NSLog(@"%g", self.player.duration);
    //        slider.maximumValue = self.player.duration;
    //    self.player.currentTime
    self.player.numberOfLoops=10;
    
#pragma mark 加背景图
    self.backImage = [[UIImageView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    [self.view addSubview:self.backImage];
    [_backImage release];
    self.backImage.image = [UIImage imageNamed:@"1155.jpg"];
    
#pragma mark 毛玻璃
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc]initWithEffect:effect];
    visualView.frame = [[UIScreen mainScreen] bounds];
    [self.backImage addSubview:visualView];
    [visualView release];
    visualView.alpha = 0.3;
    
#pragma mark 播放键
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(160, 620, 80, 80)];
    button.backgroundColor = [UIColor colorWithRed:186 / 256.0 green:33 / 256.0 blue:11 / 256.0 alpha:1];
    [self.view addSubview:button];
    [button release];
    [button setTitle:@"播放" forState:UIControlStateNormal];
    button.layer.cornerRadius = 40;
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
#pragma mark 调进度
    UISlider *slider = [[UISlider alloc]initWithFrame:CGRectMake(40, 600, 350, 10)];
    [self.view addSubview:slider];
    [slider release];
    [slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    slider.tintColor = [UIColor colorWithRed:186 / 256.0 green:33 / 256.0 blue:11 / 256.0 alpha:1];
    slider.tag = 100;
    slider.maximumValue = self.player.duration;
    
    //定时器 让slider随player播放移动
    self.firstTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(changeTime) userInfo:nil repeats:YES];
    
    
#pragma mark 开关 静音
    UISwitch *firstSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(60, 650, 200, 100)];
    //    firstSwitch.backgroundColor = [UIColor grayColor];
    [self.view addSubview:firstSwitch];
    [firstSwitch release];
    firstSwitch.onTintColor = [UIColor colorWithRed:186 / 256.0 green:33 / 256.0 blue:11 / 256.0 alpha:1];
    firstSwitch.tintColor = [UIColor grayColor];
    firstSwitch.on = YES;
    [firstSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    
#pragma mark 加减 调音量
    UIStepper *stepper = [[UIStepper alloc]initWithFrame:CGRectMake(280, 650, 100, 100)];
    stepper.backgroundColor = [UIColor colorWithRed:186 / 256.0 green:33 / 256.0 blue:11 / 256.0 alpha:1];
    stepper.tintColor = [UIColor whiteColor];
    stepper.layer.cornerRadius = 5;
    [self.view addSubview:stepper];
    [stepper release];
    [stepper addTarget:self action:@selector(stepper:) forControlEvents:UIControlEventValueChanged];
    
    
#pragma mark 转圈图
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 50, 200, 200)];
    self.imageView.backgroundColor = [UIColor yellowColor];
    
    
    self.imageView.image = [UIImage imageNamed:@"111.jpg"];
    self.imageView.layer.cornerRadius = 100;
    self.imageView.layer.masksToBounds = YES;
    
    self.imageView.layer.shadowOffset = CGSizeMake(10, 10);
    self.imageView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.imageView.layer.shadowOpacity = 1;
    self.imageView.layer.shadowRadius = 100;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(120, 30, 200, 200)];
    [self.view addSubview:view];
    [view release];
    view.layer.cornerRadius = 100;
    view.layer.shadowOffset = CGSizeMake(10, 10);
    view.layer.shadowColor = [UIColor yellowColor].CGColor;
    view.layer.shadowOpacity = 1;
    view.alpha = 0.8;
    [view addSubview:self.imageView];
    [_imageView release];
    
    
    
    
    self.a = 1;
//    [self startAnimation];
    
    //转动第三种方法初始化动画
    [self initAnimatiom];
    //先不要让动画播放
    [self pauseLayer:self.imageView.layer];
    
    
#pragma mark 歌词
    self.lrcTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 250, self.view.frame.size.width, 300) style:UITableViewStylePlain];
    [self.view addSubview:self.lrcTable];
    self.lrcTable.delegate = self;
    self.lrcTable.dataSource = self;
    self.lrcTable.backgroundColor = [UIColor clearColor];
    [self.lrcTable registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    self.lrcTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [_lrcTable release];

    // 解析歌词
    self.lrcContent = [[LrcParser alloc] init];
    [self.lrcContent parserLrc];
    
    
}


// 控制播放进度
- (void)sliderAction: (UISlider *)slider {
    NSLog(@"%f", slider.value);
    self.player.currentTime = slider.value;
    
}

//- (void)startAnimation {
//    [UIView beginAnimations:nil context:nil];
//    [UIView setAnimationDuration:0.1];
//    [UIView setAnimationDelegate:self];
//    [UIView setAnimationDidStopSelector:@selector(endAnimation)];
//    self.imageView.transform = CGAffineTransformMakeRotation(self.a * (M_PI / 180.0f));
//    [UIView commitAnimations];
//}
//
//- (void)endAnimation {
//    self.a++;
//    [self startAnimation];
//}

//- (void)timerAction {
//    self.imageView.transform = CGAffineTransformMakeRotation(self.a / (M_PI / 180.0f));
//    self.a++;
//}

- (void)initAnimatiom {
    //创建一个绕z轴选择的动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //旋转一周
    animation.toValue = @(2*M_PI);
    //循环次数，尽量大
    animation.repeatCount = MAXFLOAT;
    //执行一次动画需要的时间
    animation.duration = 50.0f;
    [self.imageView.layer addAnimation:animation forKey:@"rotationAnimation"];
}

- (void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}
- (void)resumeLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    
    
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}


- (void)buttonClick: (UIButton *)button {
    if ([button.currentTitle isEqualToString:@"播放"]) {
        [self.player play];
        [button setTitle:@"暂停" forState:UIControlStateNormal];
//        self.secTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
//        [self timerAction];
        CAAnimation * anim = [self.imageView.layer animationForKey:@"rotationAnimation"];
        if (anim == nil) {
            [self initAnimatiom];
        }else{
            [self resumeLayer:self.imageView.layer];
        }

        
        
    } else if ([button.currentTitle isEqualToString:@"暂停"]) {
        [self.player pause];
        [button setTitle:@"播放" forState:UIControlStateNormal];
//        [self.secTimer invalidate];
        //暂停封面图片的旋转
        CAAnimation * anim = [self.imageView.layer animationForKey:@"rotationAnimation"];
        if (anim) {
            //暂停动画
            [self pauseLayer:self.imageView.layer];
        }

        
    }
}

#pragma mark 开关 静音
- (void)switchAction:(UISwitch *)firstSwitch {
    NSLog(@"%d", firstSwitch.isOn);
    
    self.player.volume = firstSwitch.on;
}

#pragma mark 调音量
- (void)stepper: (UIStepper *)stepper {
    self.player.volume = stepper.value;
}

#pragma mark slider按钮随时间移动
- (void)changeTime {
    UISlider *slider = (UISlider *)[self.view viewWithTag:100];
    slider.value = self.player.currentTime;
    
#pragma mark 歌词滚动
    // 先打印下音乐播到几分几秒
    CGFloat currentTime = self.player.currentTime;
    //NSLog(@"%d:%d", (int)currentTime / 60, (int)currentTime % 60);
    
    for (int i = 0; i < self.lrcContent.timerArray.count; i++) {
        NSArray *timeArray = [self.lrcContent.timerArray[i] componentsSeparatedByString:@":"];
        float lrcTime = [timeArray[0] intValue]*60 + [timeArray[1] floatValue];
        if (currentTime > lrcTime) {
            self.currentRow = i;
            
        } else
            break;
    }
    
    [self.lrcTable reloadData];
    [self.lrcTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentRow inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    


}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.lrcContent.wordArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
    cell.textLabel.text = self.lrcContent.wordArray[indexPath.row];
    
    if (indexPath.row == self.currentRow) {
        cell.textLabel.textColor = [UIColor redColor];
        cell.textLabel.font = [UIFont systemFontOfSize:20];
    } else {
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
    }
    
    cell.textLabel.textAlignment = 1;
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
